import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/patients',
    name: 'Patients',
    component: () => import('@/views/Patients.vue'),
    meta: { title: '我的患者', requiresAuth: true }
  },
  {
    path: '/patient/:patientId/:visitId',
    name: 'PatientDetail',
    component: () => import('@/views/PatientDetail.vue'),
    meta: { title: '患者详情', requiresAuth: true },
    props: true
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫，用于实现登录拦截
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || '患者360视图'
  
  // 检查该路由是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 从本地存储获取用户信息
    const userId = localStorage.getItem('userId')
    
    // 如果没有用户信息，则跳转到登录页面
    if (!userId) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router 